package com.cms.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.cms.entity.ArcType;
import com.cms.entity.Article;
import com.cms.entity.PageBean;
import com.cms.service.ArcTypeService;
import com.cms.service.ArticleService;
import com.cms.util.NavUtil;
import com.cms.util.PageUtil;
import com.cms.util.PropertiesUtil;
import com.cms.util.StringUtil;

/**
 * 文章类别Controller类
 * @author user
 *
 */
@Controller
@RequestMapping("/arcType")
public class ArcTypeController {

	@Resource
	private ArticleService articleService;
	
	@Resource
	private ArcTypeService arcTypeService;
	
	/**
	 * 根据类型查询查询文章结果
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/{id}")
	public ModelAndView list(@PathVariable("id") Integer id,@RequestParam(value="page",required=false) String page)throws Exception{
		
		ModelAndView mav=new ModelAndView();//数据与视图的封装类
		
		Map<String,Object> map=new HashMap<String,Object>();//构造查询条件
		
		//初始page未传值指定为1
		if(!StringUtil.isNotEmpty(page)){
			page="1";
		}
		//外部文件指定分页大小
		int listPageSize=Integer.parseInt(PropertiesUtil.getValue("listPageSize"));		
		//传入当前页和分页大小，方便后面拿到start
		PageBean pageBean=new PageBean(Integer.parseInt(page),listPageSize);	
		
		//封装条件（根据栏目id查询）
		map.put("typeId", id);
		//根据目前map封装的栏目id查询文章总数（它的获取只需要一个条件）
		Long total=articleService.getTotal(map);
		
		//补充查询条件，查询对应分页结果集
		map.put("start", pageBean.getStart());
		map.put("size", pageBean.getPageSize());

		
		//目前是根据栏目id查询所有文章集合（后面还要增加多余的条件）条件增加后，查询到得是某个分页的数据
		List<Article> articleList=articleService.list(map);
		mav.addObject("articleList", articleList);
		
		//上面拿到分页数据，下面来产生分页的html代码
		//生成列表分页导航（上一页 ，下一页）
		mav.addObject("pageCode", PageUtil.genUpAndDownPagation(total.intValue(), 
				Integer.parseInt(page), 
				Integer.parseInt(PropertiesUtil.getValue("listPageSize")), 
				String.valueOf(id)));
		
		ArcType arcType=arcTypeService.findById(id);		
		mav.addObject("arcType", arcType);
		
		
		mav.addObject("navCode", NavUtil.genArticleListNavigation(arcType.getTypeName()));
		
		
		//封装跳转的视图
		mav.setViewName("articleList");		
		return mav;
	}
}

